package com.miracle9.game.server.message;

import org.apache.log4j.Logger;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.apache.mina.filter.codec.textline.LineDelimiter;

import java.nio.charset.Charset;

public class CharsetEncoderH5 implements ProtocolEncoder {

    private static Logger log = Logger.getLogger(CharsetDecoderH5.class.getName());
    private final static Charset charset = Charset.forName("UTF-8");

    @Override
    public void dispose(IoSession session) throws Exception {
    }

    @Override
    public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
        log.info("#############encode############");
        try{
          /*  IoBuffer buff = IoBuffer.allocate(100).setAutoExpand(true);
            buff.putString(message.toString(), charset.newEncoder());
            // put 当前系统默认换行符
          //  buff.putString(LineDelimiter.UNIX.getValue(), charset.newEncoder());
            // 为下一次读取数据做准备
            buff.flip();
            out.write(buff);*/

            int length = message.toString().length();
            IoBuffer buffer = IoBuffer.allocate(length);
            buffer.put(message.toString().getBytes("UTF-8"));
            buffer.flip();
            out.write(buffer);

        }catch (Exception e){
            log.error(e.getMessage());
            e.printStackTrace();
        }

    }
}
